package com.lepu.app.usercenter;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.app.application.MyApplication;
import com.app.config.AppConfig;
import com.app.utils.Const;
import com.app.utils.DspTongJi;
import com.app.utils.LoginUtil;
import com.app.utils.ObserverConst;
import com.app.utils.UmengEvent;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.EmojiFilter;
import com.core.lib.utils.ObserverManager;
import com.core.lib.utils.main.AppManager;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.main.UmengHelper;
import com.core.lib.widget.MyDialog;
import com.lepu.app.main.activity.AppBroswerActivity;
import com.lepu.app.usercenter.bean.LoginInfo;
import com.lepu.app.usercenter.util.UserCenterUtil;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;
import com.lepu.pasm.R;

public class RegisterActivity extends BaseFragmentActivity implements
		OnTopbarNewLeftLayoutListener, AsyncRequest, OnEditorActionListener {

	private static final String REQUEST_REGISTER = "request_register";
	private static final String REQUEST_GET_CODE = "request_get_code";

	private static final String REQUEST_LOGIN = "request_login";

	private static final int MSG_REGISTER_SUCCESS = 10;
	private static final int MSG_REGISTER_FAIL = 11;

	private static final int MSG_GET_CODE_SUCCESS = 20;
	private static final int MSG_GET_CODE_FAIL = 21;
	private static final int MSG_GET_CODE_UPDATE = 22;

	private static final int MSG_LOGIN_SUCCESS = 30;
	private static final int MSG_LOGIN_FAIL = 31;

	private Button mGetCodeButton;
	@SuppressWarnings("unused")
	private String mCurrentUserName = "";
	@SuppressWarnings("unused")
	private String mCurrentPwd = "";
	private String mCurrentNickName = "";
	
	private int mIsPromotion = 0;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.usercenter_register_activity);

		init();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();

		// 移除更新验证码
		mHandler.removeMessages(MSG_GET_CODE_UPDATE);
	}

	/**
	 * 添加页面动画，需要重写这个方法，
	 */
	@Override
	public void onBackPressed() {
		finishAnim(R.anim.lib_push_down_up_in, R.anim.lib_push_down_up_out);
	}

	@Override
	public void onTopbarLeftLayoutSelected() {
		finishAnim(R.anim.lib_push_down_up_in, R.anim.lib_push_down_up_out);
	}

	/**
	 * 初始化方法
	 */
	private void init() {

		// topbar
		CustomTopBarNew topbar = (CustomTopBarNew) findViewById(R.id.topbar);
		topbar.setTopbarTitle("注册");
		topbar.setonTopbarNewLeftLayoutListener(this);

		mGetCodeButton = (Button) findViewById(R.id.getCodeButton);
		TextView noCodeTextView = (TextView) findViewById(R.id.noCodeTextView);
		Button registerButton = (Button) findViewById(R.id.registerButton);
		TextView loginTextView = (TextView) findViewById(R.id.loginTextView);

		mGetCodeButton.setTag(0);
		mGetCodeButton.setOnClickListener(mOnClickListener);
		noCodeTextView.setOnClickListener(mOnClickListener);
		registerButton.setOnClickListener(mOnClickListener);
		loginTextView.setOnClickListener(mOnClickListener);
		
		EditText pwdEditText2 = (EditText) findViewById(R.id.pwdEditText2);
		pwdEditText2.setOnEditorActionListener(this);

		EditText nickNameEditText = (EditText) findViewById(R.id.nickNameEditText);
		nickNameEditText.setFilters(new InputFilter[] { new EmojiFilter(),
				new InputFilter.LengthFilter(14) });
		
		LinearLayout checkLayout = (LinearLayout) findViewById(R.id.checkLayout);
		checkLayout.setOnClickListener(mOnClickListener);
		checkLayout.setSelected(true);

		// EditText yaoQingCodeEditText = (EditText)
		// findViewById(R.id.yaoQingCodeEditText);
		// boolean flag = AppConfig.getConfigBoolean(this,
		// Const.CONFIG_APP_FIRST_REGISTER, false);
		// if(flag)
		// {
		// yaoQingCodeEditText.setVisibility(View.GONE);
		// }else{
		// yaoQingCodeEditText.setVisibility(View.VISIBLE);
		// }
	}

	private void requestGetCode() {
		EditText userEditText = (EditText) findViewById(R.id.userEditText);
		String userContent = userEditText.getText().toString().trim();

		boolean flag = UserCenterUtil.getRegisterCode(this, this,
				REQUEST_GET_CODE, userContent);
		if (flag) {
			showProgressDialog();
		}
	}

	private void requestRegister() {
		EditText userEditText = (EditText) findViewById(R.id.userEditText);
		EditText codeEditText = (EditText) findViewById(R.id.codeEditText);
		EditText pwdEditText = (EditText) findViewById(R.id.pwdEditText);
		EditText pwdEditText2 = (EditText) findViewById(R.id.pwdEditText2);

		EditText nickNameEditText = (EditText) findViewById(R.id.nickNameEditText);

		String userContent = userEditText.getText().toString().trim();
		String codeContent = codeEditText.getText().toString().trim();
		String pwdContent = pwdEditText.getText().toString().trim();
		String pwdContent2 = pwdEditText2.getText().toString().trim();
		String nickName = nickNameEditText.getText().toString().trim();

		boolean flag = UserCenterUtil.register(this, this, REQUEST_REGISTER,
				false, userContent, codeContent, pwdContent, pwdContent2,
				nickName, "", "", "", "",mIsPromotion);
		if (flag) {
			mCurrentUserName = userContent;
			mCurrentPwd = pwdContent;
			mCurrentNickName = nickName;
			showProgressDialog();
		}
	}

	private void checkCode() {

		EditText userEditText = (EditText) findViewById(R.id.userEditText);

		final String userContent = userEditText.getText().toString().trim();

		if (TextUtils.isEmpty(userContent) || userContent.length() != 11) {
			UIHelper.showToast(RegisterActivity.this,
					R.string.usercenter_user_msg);
			return;
		}

		new MyDialog(RegisterActivity.this)
				.setMessage(R.string.usercenter_code_message)
				.setNegativeButton(R.string.usercenter_code_go,
						new View.OnClickListener() {

							@Override
							public void onClick(View v) {
								requestGetCode();
							}
						})
				.setPositiveButton(R.string.usercenter_code_jump,
						new View.OnClickListener() {

							@Override
							public void onClick(View v) {

								Intent intent = new Intent(
										RegisterActivity.this,
										RegisterByQuestionActivity.class);
								intent.putExtra("phone", userContent);
								startActivity(intent, true);
							}
						}).create(null).show();
	}
	
	View.OnClickListener mOnClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.getCodeButton:

				int tag = (Integer) v.getTag();
				if (tag == 0) {
					requestGetCode();
				} else {
					checkCode();
				}
				// 不需要跳过验证
				// requestGetCode();
				break;
			case R.id.noCodeTextView:

				checkCode();
				break;
			case R.id.registerButton:

				//// 统计点击注册
				UmengHelper.CustomEvent(RegisterActivity.this,
						UmengEvent.event_sign_up);
				requestRegister();
				
				break;
			case R.id.loginTextView:

				finish(true);
				LoginUtil.jumpLogin(RegisterActivity.this);
				break;
			case R.id.checkLayout:
				
				Button registerButton = (Button) findViewById(R.id.registerButton);
				
				v.setSelected(!v.isSelected());
				if(v.isSelected())
				{
					registerButton.setEnabled(true);
					Intent intent = new Intent(RegisterActivity.this,
							AppBroswerActivity.class);
					intent.putExtra("title", "免责声明");
					intent.putExtra("no_need_menu", true);
					intent.putExtra("url", "file:///android_asset/protol/protol.html");
					startActivity(intent, true);
				}
				else{
					registerButton.setEnabled(false);
				}
				break;
			default:
				break;
			}
		}
	};

	@SuppressLint("HandlerLeak")
	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case MSG_GET_CODE_UPDATE:

				int codeText = Integer.parseInt(mGetCodeButton.getText()
						.toString());
				codeText--;

				mGetCodeButton.setText(codeText + "");
				if (codeText <= 0) {
					mHandler.removeMessages(MSG_GET_CODE_UPDATE);
					mGetCodeButton.setTag(1);
					mGetCodeButton.setText("重新获取验证码");
					mGetCodeButton.setEnabled(true);
				} else {
					mHandler.sendEmptyMessageDelayed(MSG_GET_CODE_UPDATE, 1000);
				}

				break;
			case MSG_GET_CODE_SUCCESS:
				hideProgressDialog();

				mHandler.removeMessages(MSG_GET_CODE_UPDATE);
				mGetCodeButton.setTag(0);
				mGetCodeButton.setEnabled(false);
				mGetCodeButton.setText("60");
				mHandler.sendEmptyMessageDelayed(MSG_GET_CODE_UPDATE, 1000);
				break;
			case MSG_GET_CODE_FAIL:
				hideProgressDialog();
				break;
			case MSG_REGISTER_SUCCESS:
				
				boolean flag = AppConfig.getConfigBoolean(RegisterActivity.this,
				Const.CONFIG_APP_FIRST_REGISTER,true);
				if(flag)
				{
					AppConfig.setConfig(RegisterActivity.this,
							Const.CONFIG_APP_FIRST_REGISTER, false);
					// 只需要dsp渠道,统计注册
					new DspTongJi().requestRegisterSuccess(RegisterActivity.this);
				}
		
				//现在不自动登录了
//				boolean flag = UserCenterUtil.login(RegisterActivity.this,
//						RegisterActivity.this, REQUEST_LOGIN, mCurrentUserName,
//						mCurrentPwd);
//				if (flag) {
//					showProgressDialog();
//				}
				
				hideProgressDialog();
				 finish(true);
				 
				 AppManager.getAppManager().finishActivity(LoginActivity.class);
				 //跳入完善信息
				 LoginUtil.jumpUserInfoActivity(RegisterActivity.this);
				break;
			case MSG_REGISTER_FAIL:
				hideProgressDialog();
				break;
			case MSG_LOGIN_SUCCESS:

				hideProgressDialog();

				if (LoginUtil.checkIsLogin()) {
					// 登录成功更新
					ObserverManager.getInstance().notify(
							ObserverConst.NOTIFY_MY_LOGIN_STATE_CHANGE, null,
							LoginInfo.TYPE_LOGIN);

					finishAnim(R.anim.lib_push_down_up_in,
							R.anim.lib_push_down_up_out);

					AppManager.getAppManager().finishActivity(
							LoginActivity.class);
					
					LoginUtil.jumpMainActivity(RegisterActivity.this);
				} else {
					finishAnim(R.anim.lib_push_down_up_in,
							R.anim.lib_push_down_up_out);
				}

				break;
			case MSG_LOGIN_FAIL:

				hideProgressDialog();

				finishAnim(R.anim.lib_push_down_up_in,
						R.anim.lib_push_down_up_out);
				break;

			default:
				break;
			}
		};
	};

	@Override
	public void RequestComplete(Object object, Object data) {
		if (object.equals(REQUEST_GET_CODE)) {
			String result = (String) data;
			int code = 0;
			try {
				JSONObject jsonObject = new JSONObject(result);
				JSONObject obj1 = (JSONObject) jsonObject.get("Result");
				code = obj1.optInt("Status");
			} catch (JSONException e) {
				e.printStackTrace();
			}

			if (code == 200) {
				mHandler.sendEmptyMessage(MSG_GET_CODE_SUCCESS);
			} else {
				mHandler.sendEmptyMessage(MSG_GET_CODE_FAIL);
			}
		} else if (object.equals(REQUEST_REGISTER)) {
			
			String result = (String) data;
			JSONObject dataObject = null;
			try {
				JSONObject jsonObject = new JSONObject(result);
				JSONObject obj1 = (JSONObject) jsonObject.get("Result");
				dataObject = (JSONObject) obj1.get("DetailInfo");
				
				LoginInfo loginInfo = LoginInfo.parseLoginInfo(dataObject
						.toString());
				loginInfo.NickName = mCurrentNickName;
				loginInfo.MobilePhone = mCurrentUserName;
				MyApplication.getInstance().mTempLoginInfo = loginInfo;

				mHandler.sendEmptyMessage(MSG_REGISTER_SUCCESS);
			} catch (JSONException e) {
				e.printStackTrace();
				mHandler.sendEmptyMessage(MSG_REGISTER_FAIL);
			}
			
		} else if (object.equals(REQUEST_LOGIN)) {

			String result = (String) data;
			int code = 0;
			JSONObject dataObject = null;
			try {
				JSONObject jsonObject = new JSONObject(result);
				JSONObject obj1 = (JSONObject) jsonObject.get("Result");
				code = obj1.optInt("Status");
				dataObject = (JSONObject) obj1.get("DetailInfo");
			} catch (JSONException e) {
				e.printStackTrace();
			}

			if (code == 200) {

				LoginInfo loginInfo = LoginInfo.parseLoginInfo(dataObject
						.toString());
				LoginInfo.saveLoginInfo(this, loginInfo);

				mHandler.sendEmptyMessage(MSG_LOGIN_SUCCESS);
			} else {
				mHandler.sendEmptyMessage(MSG_LOGIN_FAIL);
			}
		}
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
		if (object.equals(REQUEST_GET_CODE)) {
			mHandler.sendEmptyMessage(MSG_GET_CODE_FAIL);
		} else if (object.equals(REQUEST_REGISTER)) {
			mHandler.sendEmptyMessage(MSG_REGISTER_FAIL);
		}
		if (object.equals(REQUEST_LOGIN)) {
			mHandler.sendEmptyMessage(MSG_LOGIN_FAIL);
		}
	}

	@Override
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		switch (actionId) {
		case EditorInfo.IME_ACTION_DONE:

			requestRegister();
			break;
		}
		return true;
	}

}
